var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;
var arrx = [], arry = [], arrz = [];
var canvasw = 600, canvash = 600;

var that;
var app=getApp();
import { formatTime, formatFileTime } from '../../utils/util.js';

Page({
  /* 页面的初始数据 */
  data: {
    content:undefined,
    fileID:undefined,
    isImageSaved:false,
  },

  /* 生命周期函数--监听页面加载 */
  onLoad: function () {
    that=this;
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath() 
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },

  uploadPaint: async function (){
    if (arrx.length==0){
      wx.showModal({
        title: '提示',
        content: '图画内容不能为空！',
        showCancel: false
      });
    }
    else{
      //上传新的图片
      var tempFilePath;
      await wx.canvasToTempFilePath({
        canvasId: 'canvas',
      }).then(res=>{tempFilePath=res.tempFilePath})

      that.uploadFile(tempFilePath)
    }
  },

  uploadFile: async function (tempFilePath) {
    await wx.cloud.uploadFile({
      cloudPath: that.timetostr(new Date()),
      filePath: tempFilePath
    }).then(res=>{that.data.fileID = res.fileID;})
    //删除旧的图片
    if(app.globalData.userInfo.fileID){
        wx.cloud.deleteFile({
          fileList: [app.globalData.userInfo.fileID],
        })
    }
    app.globalData.userInfo.fileID = that.data.fileID
    await wx.cloud.callFunction({
      name:"updateUserMessage",
      data:{
        fileID:that.data.fileID,
      }
    })
    that.isImageSaved = true;
    that.setData({
      isImageSaved:true,
    })
    wx.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 2000
    })
  },

  uploadImage: async function () {
    var tempFilePath;
    await wx.chooseImage({
      count: 1,//最多一张图片 
      sourceType: ['album', 'camera'],//图片来源
    }).then(res =>{tempFilePath=res.tempFilePaths[0]})
    
    await that.uploadFile(tempFilePath)
    wx.getImageInfo({
      src: tempFilePath ,
      success(res){
            let path = res.path //本地图片路径
            let width = res.width //图片的宽
            let height = res.height //图片的高
            if(height > width){
              context.drawImage(path, 0, 0-(325*height/width-325)/2, 325, 325*height/width)
            }
            else{
              context.drawImage(path, 0-(325*width/height-325)/2,0,325*width/height, 325)
            }
            context.draw()
      }
    })
  },

  stateSubmit: async function (e) {
    var content=e.detail.value['input-content'];
    that.content=content;
    if (content.trim()==''){
      wx.showModal({
        title: '提示',
        content: '文字内容不能为空！',
        showCancel: false
      });
    }
    else{
      wx.showLoading({
        title: '正在上传动态',
        mask: true
      })
      await wx.cloud.callFunction({
        name:"updateUserState",
        data:{
          fileID:that.data.fileID,
          content:that.content,
          userInfo:app.globalData.userInfo,
          date:formatTime(new Date()),
        }
      })
      //删除就动态图片
      if(app.globalData.userInfo.stateFileID){
        wx.cloud.deleteFile({
          fileList: [app.globalData.userInfo.stateFileID],
        })
      }
      app.globalData.userInfo.stateFileID = that.data.fileID
      app.globalData.userInfo.fileID = null
      wx.cloud.callFunction({
        name:"updateUserMessage",
        data:{
          stateFileID:that.data.fileID,
          fileID:null
        }
      })
      wx.hideLoading()
      that.isImageSaved=false;
      wx.switchTab({url: '/pages/index/index',})
    }
  },
  
  timetostr:function(time){
    var randnum = Math.floor(Math.random() * (9999 - 1000)) + 1000;
    var str = randnum +"_"+ formatFileTime(time) + ".png";
    return str;
  },

  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },
  canvasStart: function (event){
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  },
  canvasMove: function (event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    }; 
    
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };

    };
    context.clearRect(0, 0, canvasw, canvash);

    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
    context.draw(false)
  },
  canvasEnd: function (event) {
    isButtonDown = false; 
  },
  cleardraw: function () {
    arrx = [], arry = [],  arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  }
  
})